/**
 * @file servertester.cpp
 * @brief Server automated tests implementation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * @author VestniK (Sergey N.Vidyuk) sir.vestnik@gmail.com
 * @date 17 Oct 2008
 */
#include <QtTest/QtTest>
#include <QtCore/QThread>
#include <QtNetwork/QTcpSocket>

#include <memory>

#include "server.h"
#include "enumstostr.h"
#include "client.h"
#include "playerclient.h"

class ServerTester:public QObject {
    Q_OBJECT
    private slots:
        void initTestCase();
        void cleanupTestCase();

        void ConnectionTests();
};

using namespace mjn;

class ServerThread:public QThread {
    protected:
        void run() {
            Server server;
            exec();
        }
};

ServerThread *server = 0;

void ServerTester::initTestCase() {
    server = new ServerThread;
    server->start();
}

void ServerTester::cleanupTestCase() {
    server->quit(); // Ask thread to stop event loop
    server->wait(); // wait until thread stops.
    delete server;
}

void ServerTester::ConnectionTests() {
    Client clients[PLAYERS_COUNT+1];
    for ( int i = 0; i < PLAYERS_COUNT+1; i++ ) {
        QSignalSpy connectedSpy(&clients[i],SIGNAL(connected()));
        QSignalSpy errorSpy(&clients[i],SIGNAL(connectionError(QString)));
        QSignalSpy connectionFailedSpy(&clients[i],SIGNAL(connectionFailed()));
        clients[i].connectToHost("localhost");
        QTest::qWait(200); // waiting 200ms until connection will be established
        if ( i < PLAYERS_COUNT ) {
            QCOMPARE( connectedSpy.count() , 1 );
            QCOMPARE( errorSpy.count() , 0 );
            QCOMPARE( connectionFailedSpy.count() , 0 );
        } else {
            QCOMPARE( connectedSpy.count() , 0 );
            QCOMPARE( errorSpy.count() , 1 );
            QCOMPARE( connectionFailedSpy.count() , 1 );
        }
    }
}

QTEST_MAIN(ServerTester);

#include "servertester.moc"
